package com.duojuhe.common.utils.jsonutils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.duojuhe.common.result.ServiceResult;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 *json操作工具类
 **/
public class JsonUtils {

    private final static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(new JavaTimeModule());
    }

    private JsonUtils() {

    }

    /**
     * 获取objectMapper实例
     */
    public static ObjectMapper getInstance() {
        return objectMapper;
    }

    /**
     * javaBean、列表数组转换为json字符串
     */
    public static String objToJson(Object obj) {
        try {
            if (obj==null || "null".equals(obj)){
                return null;
            }
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * javaBean、列表数组转换为json字符串,忽略空值
     */
    public static String objToJsonIgnoreNull(Object obj) throws Exception {
       try {
           if (obj==null){
               return null;
           }
           ObjectMapper mapper = new ObjectMapper();
           mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
           return mapper.writeValueAsString(obj);
       } catch (JsonProcessingException e) {
           e.printStackTrace();
           return null;
       }
    }


    /**
     * json 转对象
     */
    public static <T> T jsonToObj(String jsonString, Class<T> clazz) {
        //允许出现单引号
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        //接受只有一个元素的数组的反序列化
        objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        try {
            return objectMapper.readValue(jsonString, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * json字符串转换为map
     */
    public static <T> Map<String, Object> jsonToMap(String jsonString) {
        try {
            if (StringUtils.isBlank(jsonString)){
                return null;
            }
            ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            return mapper.readValue(jsonString, Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static <T> JsonNode jsonToJsonNode(String jsonString) {
        try {
            if (StringUtils.isBlank(jsonString)){
                return null;
            }
            ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            return mapper.readValue(jsonString, JsonNode.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }

    }


    /**
     * json字符串转换为map
     */
    public static <T> Map<String, T> jsonToMap(String jsonString, Class<T> clazz) throws Exception {
        Map<String, Map<String, Object>> map = (Map<String, Map<String, Object>>) objectMapper.readValue(jsonString, new TypeReference<Map<String, T>>() {
        });
        Map<String, T> result = new HashMap<String, T>();
        for (Map.Entry<String, Map<String, Object>> entry : map.entrySet()) {
            result.put(entry.getKey(), mapToObj(entry.getValue(), clazz));
        }
        return result;
    }

    /**
     * 深度转换json成map
     *
     * @param json
     * @return
     */
    public static Map<String, Object> jsonToMapDeeply(String json) throws Exception {
        return jsonToMapRecursion(json, objectMapper);
    }

    /**
     * 把json解析成list，如果list内部的元素存在jsonString，继续解析
     *
     * @param json
     * @param mapper 解析工具
     * @return
     * @throws Exception
     */
    private static List<Object> jsonToListRecursion(String json, ObjectMapper mapper) throws Exception {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        List<Object> list = mapper.readValue(json, List.class);
        for (Object obj : list) {
            if (obj != null && obj instanceof String) {
                String str = (String) obj;
                if (str.startsWith("[")) {
                    obj = jsonToListRecursion(str, mapper);
                } else if (obj.toString().startsWith("{")) {
                    obj = jsonToMapRecursion(str, mapper);
                }
            }
        }
        return list;
    }

    /**
     * 把json解析成map，如果map内部的value存在jsonString，继续解析
     *
     * @param json
     * @param mapper
     * @return
     * @throws Exception
     */
    private static Map<String, Object> jsonToMapRecursion(String json, ObjectMapper mapper) throws Exception {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        Map<String, Object> map = mapper.readValue(json, Map.class);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            Object obj = entry.getValue();
            if (obj != null && obj instanceof String) {
                String str = ((String) obj);

                if (str.startsWith("[")) {
                    List<?> list = jsonToListRecursion(str, mapper);
                    map.put(entry.getKey(), list);
                } else if (str.startsWith("{")) {
                    Map<String, Object> mapRecursion = jsonToMapRecursion(str, mapper);
                    map.put(entry.getKey(), mapRecursion);
                }
            }
        }

        return map;
    }

    /**
     * 与javaBean json数组字符串转换为列表
     */
    public static <T> List<T> jsonToList(String jsonArrayStr, Class<T> clazz) {

        JavaType javaType = getCollectionType(ArrayList.class, clazz);
        List<T> lst = null;
        try {
            lst = (List<T>) objectMapper.readValue(jsonArrayStr, javaType);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return lst;
    }


    /**
     * 获取泛型的Collection Type
     *
     * @param collectionClass 泛型的Collection
     * @param elementClasses  元素类
     * @return JavaType Java类型
     * @since 1.0
     */
    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }


    /**
     * map  转JavaBean
     */
    public static <T> T mapToObj(Map map, Class<T> clazz) {
        return objectMapper.convertValue(map, clazz);
    }


    /**
     * map  转JavaBean
     */
    public static <T> T objToObj(Object obj, Class<T> clazz) {
        return objectMapper.convertValue(obj, clazz);
    }


    public static void write(ServletResponse response, ServiceResult result){
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            out = response.getWriter();
            out.println(JSON.toJSONString(result));
        } catch (Exception e) {

        }finally {
            if(out!=null){
                out.flush();
                out.close();
            }
        }
    }


    /**
     * 判断是不是ajax请求
     *
     * @param request
     * @return
     */
    public static boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null
                && "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
    }

    /**
     * 判断一个字符串是不是json格式
     *
     * @param jsonString
     * @return
     */
    public static JSONObject isGoodJson(String jsonString) {
        try {
            if (StringUtils.isEmpty(jsonString)) {
                return null;
            }
            return (JSONObject) JSONObject.parse(jsonString);
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 判断一个字符串是不是json格式
     *
     * @param jsonString
     * @return
     */
    public static boolean isJson(String jsonString) {
        try {
            if (StringUtils.isBlank(jsonString)) {
                return false;
            }
            JSONObject.parse(jsonString);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 将map转成json
     *
     * @param map
     * @return
     */
    public static String mapToJson(Map map) {
        try {
            if (map==null){
                return "";
            }
            // 返回值Map
            Map returnMap = new HashMap();
            Iterator entries = map.entrySet().iterator();
            Map.Entry entry;
            String name = "";
            String value = "";
            while (entries.hasNext()) {
                entry = (Map.Entry) entries.next();
                name = (String) entry.getKey();
                Object valueObj = entry.getValue();
                if (null == valueObj) {
                    value = "";
                } else if (valueObj instanceof String[]) {
                    String[] values = (String[]) valueObj;
                    for (String s : values) {
                        value = s + ",";
                    }
                    value = value.substring(0, value.length() - 1);
                } else {
                    value = valueObj.toString();
                }
                returnMap.put(name, value);
            }
            return JSON.toJSONString(returnMap);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 对象转json字符串
     */
    public static String toJsonString(Object obj) {
        return JSON.toJSONString(obj);
    }


}
